﻿// ===============================================================================
// XCI.WinForm.Platform 西安交通信息WinForm开发框架 2019 版权所有
// ===============================================================================
using System;
using System.Collections.Generic;
using XCI.Sys.Model;
using XCI.Core;
using XCI.Helper;
using XCI.Windows.Extensions;

namespace XCI.Sys.Service
{
    /// <summary>
    /// 系统模块服务
    /// </summary>
    public class ModuleService : BaseService<SysModule>
    {
        public static readonly ModuleService Instance = new ModuleService();
        protected override string RootUrl => "/api/sys/module/";

        /// <summary>
        /// 新建菜单模块模型
        /// </summary>
        public SysModule NewMenu()
        {
            return new SysModule
            {
                Id = NewId(),
                WebFlag = false,
                WinFlag = false,
                ExpandFlag = false,
                PublicFlag = false,
                DialogFlag = false,
                MenuFlag = true,
                VectorGraphFlag = false,
                PreloadingFlag = false,
                Status = true
            };
        }

        /// <summary>
        /// 新建权限模块模型
        /// </summary>
        public SysModule NewPermission()
        {
            return new SysModule
            {
                Id = NewId(),
                WebFlag = false,
                WinFlag = false,
                ExpandFlag = false,
                PublicFlag = false,
                DialogFlag = false,
                MenuFlag = false,
                VectorGraphFlag = false,
                PreloadingFlag = false,
                Status = true
            };
        }

        /// <summary>
        /// 复制模块模型
        /// </summary>
        /// <param name="original">原模型</param>
        public SysModule Copy(SysModule original)
        {
            if (original == null) throw new ArgumentNullException(nameof(original));
            var model = original?.Clone();
            model.Id = NewId();
            return model;
        }

        /// <summary>
        /// 检查模块主键是否存在
        /// </summary>
        /// <param name="id">模块主键</param>
        public bool ExistById(string id)
        {
            return ExistByIdCore(id);
        }

        /// <summary>
        /// 检查模块编码是否存在
        /// </summary>
        /// <param name="code">模块编码</param>
        public bool ExistByCode(string code)
        {
            return ExistByCodeCore(code);
        }

        /// <summary>
        /// 新建模块
        /// </summary>
        /// <param name="model">模块模型对象</param>
        /// <returns>成功返回true</returns>
        public bool Insert(SysModule model)
        {
            return InsertCore(model);
        }

        /// <summary>
        /// 修改模块
        /// </summary>
        /// <param name="model">模块模型对象</param>
        /// <returns>成功返回true</returns>
        public bool Update(SysModule model)
        {
            return UpdateCore(model);
        }

        /// <summary>
        /// 修改状态
        /// </summary>
        /// <param name="ids">主键字符串</param>
        /// <param name="status">状态,1启用;0禁用</param>
        /// <returns>成功返回true</returns>
        public bool UpdateStatus(string ids, bool status)
        {
            return UpdateStatusByIdsCore(ids, status);
        }

        /// <summary>
        /// 批量修改字段值
        /// </summary>
        /// <param name="keyValues">修改的数据集合</param>
        /// <returns>成功返回true</returns>
        public bool BatchUpdateValues(List<PrimaryKeyValue> keyValues)
        {
            return BatchUpdateValuesCore(keyValues);
        }

        /// <summary>
        /// 删除模块
        /// </summary>
        /// <param name="ids">主键字符串</param>
        /// <returns>成功返回true</returns>
        public bool Delete(string ids)
        {
            return DeleteByIdsCore(ids);
        }

        /// <summary>
        /// 根据主键获取模块对象
        /// </summary>
        /// <param name="id">模块主键</param>
        public SysModule SelectById(string id)
        {
            return SelectByIdCore(id);
        }

        /// <summary>
        /// 根据模块编码获取模块对象
        /// </summary>
        /// <param name="code">模块编码</param>
        /// <returns>成功返回模型对象</returns>
        public SysModule SelectByCode(string code)
        {
            return SelectByCodeCore(code);
        }

        /// <summary>
        /// 获取节点的直系子节点数
        /// </summary>
        /// <param name="id">模块主键</param>
        public int SelectChildCount(string id)
        {
            var url = GetUrl("selectChildCount", id);
            return SysRuntime.Api.Post<int>(url).EnsureSuccess().Data;
        }

        /// <summary>
        /// 查询模块列表
        /// </summary>
        /// <param name="status">状态(false:禁用;true:启用;null:全部记录)</param>
        public List<SysModule> SelectList(bool? status)
        {
            var map = Map.New.Add(SysConst.FStatusName, status);
            return SelectListCore(map);
        }

        /// <summary>
        /// 导出模块列表
        /// </summary>
        /// <param name="status">状态(false:禁用;true:启用;null:全部记录)</param>
        public byte[] Export(bool? status)
        {
            var map = Map.New.Add(SysConst.FStatusName, status);
            return ExportCore(map);
        }

        /// <summary>
        /// 根据用户主键查询模块列表
        /// </summary>
        /// <param name="userId">用户主键</param>
        public List<SysModule> SelectListByUserId(string userId)
        {
            var url = GetUrl("selectListByUserId", userId);
            return SysRuntime.Api.Post<List<SysModule>>(url).EnsureSuccess().Data;
        }

        /// <summary>
        /// 从缓存中查询用户模块列表
        /// </summary>
        /// <param name="userId">用户主键</param>
        public List<SysModule> SelectCacheListByUserId(string userId)
        {
            var url = GetUrl("selectCacheListByUserId", userId);
            return SysRuntime.Api.Post<List<SysModule>>(url).EnsureSuccess().Data;
        }

        /// <summary>
        /// 清除用户模块缓存
        /// </summary>
        /// <param name="userId">用户主键</param>
        public bool ClearUserModuleCache(string userId)
        {
            var url = GetUrl("clearUserModuleCache", userId);
            return SysRuntime.Api.PostAsMessage(url).EnsureSuccess().Success;
        }

        /// <summary>
        /// 新建对象关联模块
        /// </summary>
        /// <param name="objectId">对象主键</param>
        /// <param name="moduleIds">模块主键数组字符串</param>
        public bool SaveModuleMap(string objectId, string moduleIds)
        {
            var url = GetUrl("saveModuleMap");
            var map = Map.New.Add("objectId", objectId).Add("moduleIds", moduleIds);
            return SysRuntime.Api.PostAsMessage(url, map).EnsureSuccess().Success;
        }

        /// <summary>
        /// 根据对象主键删除关联模块
        /// </summary>
        /// <param name="objectId">对象主键</param>
        public bool DeleteModuleMapByObjectId(string objectId)
        {
            var url = GetUrl("deleteModuleMapByObjectId", objectId);
            return SysRuntime.Api.PostAsMessage(url).EnsureSuccess().Success;
        }

        /// <summary>
        /// 根据对象主键查询关联模块主键集合
        /// </summary>
        /// <param name="objectId">对象主键</param>
        public List<string> SelectModuleMapArrayByObjectId(string objectId)
        {
            var url = GetUrl("selectModuleMapArrayByObjectId", objectId);
            return SysRuntime.Api.Post<List<string>>(url).EnsureSuccess().Data;
        }

        /// <summary>
        /// 根据对象主键查询关联模块对象列表
        /// </summary>
        /// <param name="objectId">对象主键</param>
        public List<SysModule> SelectModuleMapListByObjectId(string objectId)
        {
            var url = GetUrl("selectModuleMapListByObjectId", objectId);
            return SysRuntime.Api.Post<List<SysModule>>(url).EnsureSuccess().Data;
        }

        /// <summary>
        /// 添加标准权限项
        /// </summary>
        /// <param name="parentModel">上级模型</param>
        public bool AddStandardPermissionModel(SysModule parentModel)
        {
            var permissions = new List<KeyValue>
            {
                new KeyValue("查询", "select"),
                new KeyValue("新建", "insert"),
                new KeyValue("修改", "update"),
                new KeyValue("删除", "delete"),
                new KeyValue("导出", "export")
            };
            return AddStandardPermissionModelCore(parentModel, permissions).EnsureSuccess().Success;
        }

        private BoolMessage AddStandardPermissionModelCore(SysModule parentModel, List<KeyValue> permissions)
        {
            var results = new List<BoolMessage>();
            foreach (var item in permissions)
            {
                SysModule module = ModuleService.Instance.NewPermission();
                module.ParentId = parentModel.Id;
                module.Name = item.Key;
                module.Code = $"{parentModel.Code}.{item.Value}";
                if (ExistByCode(module.Code))
                {
                    results.Add(new BoolMessage(false, $"模块编码 {module.Code} 已经存在"));
                }
                else if (!Insert(module))
                {
                    results.Add(new BoolMessage(false, $"模块 {module.Code} 添加失败"));
                }
            }
            return BoolMessage.MergeBoolMessage(results.ToArray());
        }
    }
}